<?php

namespace app\api\controller;
use app\api\logic\DataWechatLogic;
use app\api\model\DataAddresser;
use app\api\model\DataCity;
use app\api\model\DataUser;
use app\api\model\DataUserAccount;
use app\api\model\DataUserCommission;
use app\api\model\ShopOrderDetail;
use app\api\model\ShopOrderSend;
use expressage\Kd100;
use think\admin\Controller;

use app\data\service\OrderService;
use think\Request;
/**
 * Class Order
 * @package app\api\controller
 */
class Order extends Controller
{
    protected $middleware = ['check','auth'];

    private $orderModel;
    private $default_type = 'json';
    private $orderStatus = array(
        '已取消','预订单','待支付','支付中','已支付','已发货','已完成','已退货'
    );
    public function __construct(Request $request){
        $this->request = $request;
        $this->orderModel = new \app\api\model\ShopOrder();
    }
    //获取发票须知
    public function invoiceInstructions(){
        $detail = sysconf('invoiceInstructions');
        if(empty($detail)) $detail = '';
        return \Tools::returnMsg(true,array(
            'content'   => $detail
        ),$this->default_type);
    }

    /**
     * 校验渠道码
     * @param $channel
     * @param $channel_code
     * @return bool
     */
    private static function checkCheckCode($channel,$channel_code){
        if(empty($channel_code) === FALSE){
            //查询渠道类型
            $first_search = DataWechatLogic::getInfo(array(
                'code'  => $channel_code,
                'channel'  => $channel,
            ),'id,salt,check_pwd,channel');
            if(empty($first_search) === FALSE){
                return array(
                        $channel,$channel_code
                    );
            }
        }
        return array(
            0,0
        );
    }
    /**
     * 下订单
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function placeorder(){
        if($this->request->debug != 1) {
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo)){
                return \Tools::returnMsg(false,array(
                    'code'  => '100001',
                    'message'=>'未登录  请先登录'
                ),$this->default_type);
            }
            $from = input('from', 0);//0  订单确认页   1  支付
            $share_user_code = input('share_user_code', '');//分销员编号
            $channel_code = input("channel_code",'','trim');//渠道编号
            $channel = input("channel",0,'trim');//渠道类型
            $channelData = self::checkCheckCode($channel,$channel_code);
            $channel = $channelData[0];
            $channel_code = $channelData[1];
            //TODO 支付成功关联上下级关系
            //获取购物车选择商品
            $product_id = input('goods_id',0,'trim,intval');//商品id  不传 判断为从购物车中来
            $goodsids = [];
             $shopCartModel = new \app\api\model\ShopCart();
            if($product_id > 0){
                $goods_num = input('goods_num',0,'trim,intval');//商品数量
                if($goods_num == 0){
                    return \Tools::returnMsg(false,array(
                        'code'  => '1000010',
                        'message'=>'商品数量有误'
                    ),$this->default_type);
                }else{
                    $goodsids[] = array(
                        'goods_id'  =>$product_id,
                        'goods_num' =>$goods_num
                    );
                }
            }else{
                $goodsids = $shopCartModel->getLists(array(
                    'user_id' => $tokeninfo['id'],
                    'select' => 1
                ), 'goods_id,goods_num');
                if (empty($goodsids)) {
                    return \Tools::returnMsg(false, array(
                        'code' => '10004',
                        'message' => '购物车不能为空'
                    ), $this->default_type);
                }
            }
                $goodsdetailModel = new \app\api\model\ShopGoodsItem();
                $goodsModel = new \app\api\model\ShopGoods();
                $goodsList = [];
                $goods_total_price = 0;
                $goods_num = 0;
                $limit_max_num = sysconf('base.limit_max_num');
                foreach ($goodsids as &$gv) {
                    //判断库存
                    $goodsInfo = $goodsdetailModel->getOne(array(
                        'id' => $gv['goods_id']
                    ), 'id,goods_spec,name,cover,price_selling,stock_total,goods_sku,goods_code,price_market');

                    if ($goodsInfo['stock_total'] < $gv['goods_num']) {
                        return \Tools::returnMsg(false, array(
                            'code' => '10005',
                            'message' => '库存不足'
                        ), $this->default_type);
                    }
                    $goods_total_price += $goodsInfo['price_selling'] * $gv['goods_num'];
                    $goods_num += $gv['goods_num'];
                    $goodsInfo['select_num'] = $gv['goods_num'];
                    $goodsInfo['goods_spec'] = '默认';
                    $goodsList[] = $goodsInfo;
                    if($limit_max_num > 0){
                        //限制购买数量
                        if($gv['goods_num'] > $limit_max_num){
                            return \Tools::returnMsg(false, array(
                                'code' => '10005',
                                'message' => '该商品已达购买上限，请调整后重新下单'
                            ), $this->default_type);
                        }
                    }
                }
                $finial_pay = 0;
                $postage_pay = sysconf('base.postage_pay');
                $has_postage_paylimit = sysconf('base.has_postage_paylimit');
                if(!isset($has_postage_paylimit) || empty($has_postage_paylimit)) $has_postage_paylimit = 108;
                //TODO 计算运费
                //TODO 获取用户默认地址
                //获取用户佣金余额
                $is_show_commission = 0;
                $commissModel = new \app\api\model\DataUserAccount();
                $commissionInfo = $commissModel->getOne(array(
                    'uuid' => $tokeninfo['id']
                ), 'id,avail_amount,avail_credit,freeze_amount');
                $availAmount = 0;
                if (empty($commissionInfo) === FALSE) {
                    $is_show_commission = 1;
                    $availAmount = $commissionInfo['avail_amount']-$commissionInfo['freeze_amount'];
                }

                $rate = 1;
                $can_show_newActiviy = sysconf('base.can_show_newActiviy');
                if($can_show_newActiviy == 1){
                    $rate = sysconf("base.newopenActivity_rate");
                }
                if ($from == 0) {
                    //确认订单
                    $finial_pay = $goods_total_price * $rate;
                    $availAmount = max(0,min($finial_pay,$availAmount));
                    return \Tools::returnMsg(true, array(
                        'goods_list' => $goodsList,
                        'goods_num' => $goods_num,
                        'is_show_coupon' => 0,//是否显示优惠券入口  TODO 优惠券功能
                        'is_show_commission' => $is_show_commission,//是否显示佣金抵扣入口
                        'is_show_bill' => 1,//是否显示发票开具入口
                        'postage_amount' => $postage_pay,
                        'has_postage_paylimit' => $has_postage_paylimit,
                        'avail_amount' => sprintf("%.2f", $availAmount / 100),//可用佣金
                        'total_amount' => sprintf("%.2f", $goods_total_price / 100),//商品总价
                        'finial_amount' => sprintf("%.2f", $finial_pay / 100),//最终支付金额
                        'discount_amount' => sprintf("%.2f", ($goods_total_price-$finial_pay) / 100),//优惠金额
                        'address' => array(
                            'address' => '',
                            'id' => '',
                            'username' => '',
                            'phone' => ''
                        )
                    ));
                } else {
                    //计算优惠
                    //锁库存
                    //生产未支付订单
                    //唤起支付参数
                    $address = input('address', '', 'trim');//地址
                    $mobile = input('mobile', '', 'trim');//电话
                    $username = input('username', '', 'trim');//联系人
                    $coupon_id = input('coupon_id', '', 'trim');//优惠券id
                    $score = input('score', 0, 'trim');//积分
                    $selectAmount = input('select_mount', 0, 'trim');//佣金
                    $can_use_money = input('can_use_money', 0, 'trim');//1 使用佣金  0不使用佣金
                    $order_remark = input('order_remark', 0, 'trim');//用户备注
                    $isbill = input("isget_bill",0,'trim,intval');//0  不要发票  1  要发票
                    $bill_type = input('bill_type',0,'trim,intval');//0  企业  1  个人
                    $bill_name = input('bill_name','','trim');//发票抬头
                    $bill_no    = input('bill_no','','trim');//发票税号
                    $bill_product_type = input('bill_product_type',0,'trim,intval');//发票内容
                    $bill_email = input('bill_email','','trim');//接收电子发票邮箱
                    //若是企业  名称和税号必填
                    //若是个人  只填名字即可
                    if($isbill == 1){
                        if($bill_type == 0){
                            if(empty($bill_name) || empty($bill_no) || empty($bill_email)){
                                return \Tools::returnMsg(false, array(
                                    'code' => '100013',
                                    'message' => '发票信息填写不全'
                                ), $this->default_type);
                            }
                        }else{
                            if(empty($bill_name) || empty($bill_email)){
                                return \Tools::returnMsg(false, array(
                                    'code' => '100013',
                                    'message' => '发票信息填写不全'
                                ), $this->default_type);
                            }
                        }
                    }
                    if (empty($address)) {
                        return \Tools::returnMsg(false, array(
                            'code' => '90003',
                            'message' => '收货地址必填'
                        ), $this->default_type);
                    }
                    if ($selectAmount * 100 > $availAmount && $can_use_money == 1) {
                        return \Tools::returnMsg(false, array(
                            'code' => '100010',
                            'message' => '可用佣金不足'
                        ), $this->default_type);
                    }
                    //TODO 判断优惠券
                    //TODO 判断积分
                    $opera = [];
                    $this->orderModel->startTrans();//开启事务
                    $order_no = \Tools::createOrder($tokeninfo['id']);
                    $goods_total_price = sprintf("%.2f",$goods_total_price/100);
                    if($goods_total_price > $has_postage_paylimit){
                        $postage_pay = 0;//包邮
                    }
                    $res_dis_total_price = sprintf("%.2f",$goods_total_price * $rate);
                    $finial_amount = ($res_dis_total_price + $postage_pay) * 100;
                    if($can_use_money == 1){
                        $finial_amount-= $selectAmount * 100;
                    }
                    $title = '';
                    $shopOrderDetailModel = new \app\api\model\ShopOrderDetail();
                    //加入订单商品详情表
                    //扣减库存
                    $detailListData = [];
                    foreach ($goodsList as &$resv) {
                        $detailListData[] = array(
                            'order_no' => $order_no,
                            'goods_sku' => $resv['goods_sku'],
                            'goods_code' => $resv['goods_code'],
                            'goods_spec' => $resv['goods_spec'],
                            'goods_name' => $resv['name'],
                            'goods_cover' => $resv['cover'],
                            'goods_abridgeimg' => $resv['cover'],
                            'price_market' => $resv['price_market'],
                            'price_selling' => $resv['price_selling'],
                            'product_id' => $resv['id'],
                            'stock_sales' => $resv['select_num'],
                            'uuid' => $tokeninfo['id'],
                            'create_at' => \Tools::getDateTimeByTime()
                        );
                        //冻结库存
                        $opera[] = $goodsModel->incNum(array(
                            'code' => $resv['goods_code']
                        ), 'freeze_stock', $resv['select_num']);
                        $opera[] = $goodsdetailModel->incNum(array(
                            'goods_sku' => $resv['goods_sku']
                        ), 'freeze_stock', $resv['select_num']);
                        $opera[] = $goodsModel->decNum(array(
                            'code' => $resv['goods_code']
                        ), 'stock_total', $resv['select_num']);
                        $opera[] = $goodsdetailModel->decNum(array(
                            'goods_sku' => $resv['goods_sku']
                        ), 'stock_total', $resv['select_num']);
                    }
                    if (count($detailListData) > 1) {
                        $opera[] = $shopOrderDetailModel->addInfo($detailListData);
                    } else {
                        $opera[] = $shopOrderDetailModel->addData($detailListData[0]);
                    }
                    $spbill_create_ip = \Tools::getRemoteAddr();    // 客户端ip
                    //插入订单表
                    $puid1 = 0;
                    $disUser = new \app\api\model\DataUser();
                    //判断当前用户是否绑定过
                    $disUserinfo = $disUser->getOne(array(
                        'id'    => $tokeninfo['id']
                    ),'pre_dis_id');
                    if(empty($share_user_code) === FALSE){
                        if($disUserinfo['pre_dis_id'] > 0){
                            $puid1 = $disUserinfo['pre_dis_id'];
                        }else {
                            //若未绑定则读取
                            //否则不读取
                            $disuserinfo = $disUser->getOne(array(
                                'distribution_code' => $share_user_code
                            ), 'id');
                            $puid1 = empty($disuserinfo) === FALSE ? $disuserinfo['id'] : 0;
                        }
                    }else{
                        //查询
                        if($disUserinfo['pre_dis_id'] > 0){
                            $puid1 = $disUserinfo['pre_dis_id'];
                        }
                    }
                    $data = array(
                        'order_no' => $order_no,
                        'amount_total' => $res_dis_total_price * 100,
                        'amount_reduct' => 0,
                        'amount_express' => $postage_pay * 100,
                        'payment_type' => 0,
                        'payment_trade' => '',
                        'payment_amount' => $finial_amount,
                        'payment_balance' => $selectAmount*100,
                        'credit' => 0,
                        'payment_credit' => 0,
                        'payment_coupon' => 0,
                        'coupon_id' => 0,
                        'payment_remark' => '',
                        'number_goods' => $goods_num,
                        'order_remark' => $order_remark,
                        'status' => 2,
                        'expire_at' => \Tools::getDateTimeByTime(time() + 7200),
                        'spbill_create_ip' => $spbill_create_ip,
                        'create_at' => \Tools::getDateTimeByTime(),
                        'uuid' => $tokeninfo['id'],
                        'puid1' => $puid1,
                        'channel'=>$channel,
                        'channel_code'=>$channel_code,
                        'discount' => $goods_total_price-$res_dis_total_price,
                        'getbill' => $isbill,
                        'order_detail' => json_encode(array(
                            'openid' => $tokeninfo['id'],
                            'share_user_code' => $share_user_code
                        )),
                        'date' => \Tools::getDateTimeByTime(time(), 'Y-m-d'),
                    );
                    if (empty($address) === FALSE) {
                        $data['address'] = $address;
                        $data['phone'] = $mobile;
                        $data['username'] = $username;
                    }
                    $opera[] = $this->orderModel->addData($data);
                    //记录发票申请
                    if($isbill == 1){
                        //需要发票
                        $billmodel = new \app\api\model\ShopOrderBill();
                        $opera[] = $billmodel->addData(array(
                            'uuid'  =>$tokeninfo['id'],
                            'order_no'  =>$order_no,
                            'create_at' =>\Tools::getDateTimeByTime(),
                            'bill_type' => $bill_type,
                            'bill_name' => $bill_name,
                            'bill_no' => $bill_no,
                            'bill_product_type' => $bill_product_type,
                            'bill_email' => $bill_email
                        ));
                    }
                    //冻结佣金
                    if($selectAmount > 0){
                        //冻结
                        $opera[] = $commissModel->incNum(array(
                            'id'    => $commissionInfo['id']
                        ),'freeze_amount',$selectAmount * 100);
                    }
                    if (\Tools::checkArrayResult($opera)) {
                        if($finial_amount > 0) {
                             $this->orderModel->commit();
                            $body = sysconf('app_name') . '订单';
                            $notify_url = $this->request->domain() . '/index/Order/mallnotify';      // 微信服务器异步通知
                            $total_fee = $finial_amount;                // 支付金额, 单位：分
                            $time_start = \Tools::getDateTimeByTime();
                            $time_expire = \Tools::getDateTimeByTime(time() + 7200);
                            $trade_type = 'JSAPI';
                            $mech_id = sysconf('merchant_no');
                            $appid = sysconf('wx_appid');
                            $key = sysconf('token');
                            // 实例微信支付基类
                            $weixinPay = new \Wxinpay($trade_type, $tokeninfo['openid'], $order_no, $body, $total_fee, $notify_url, $spbill_create_ip, 0, $appid, $mech_id, $key);

                            // 发起微信支付
                            $result = $weixinPay->pay();
                            if ($result['code'] == 0) {      // 统一下单出错
                                $this->orderModel->saveData(array(
                                    'order_no' => $order_no
                                ), array(
                                    'status' => 0,
                                    'payment_remark' => $result['msg'],
                                    'update_at' => \Tools::getDateTimeByTime()
                                ));
                                return \Tools::returnMsg(false, array(
                                    'code' => '10041',
                                    'message' => '订单生成失败'
                                ));
                            }
                            // 获取预支付返回参成功
                            $prepay_id = $result['msg']['prepay_id'];
                            $res = $this->orderModel->saveData(array(
                                'order_no' => $order_no
                            ), array(
                                'payment_trade' => $prepay_id,
                                'payment_remark' => json_encode($result['msg']),
                                'spbill_create_ip' => $spbill_create_ip,
                                'update_at' => \Tools::getDateTimeByTime()
                            ));
                            if ($res === false) {
                                return \Tools::returnMsg(false, array(
                                    'code' => '10041',
                                    'message' => '订单生成失败'
                                ));
                            }
                            $result['msg']['time_expire'] = $time_expire;
                            unset($result['msg']['appId']);
                            $rrr = $result['msg'];
                            $rrr['total_fee'] = sprintf("%.2f", $total_fee / 100);
                            $rrr['body'] = $body;
                            $rrr['merchant'] = sysconf('app_name') . '平台';
                            $rrr['order_no'] = $order_no;
                            $rrr['pay_channel'] = 1;//1  微信支付  2  佣金抵扣
                            return \Tools::returnMsg(true, $rrr, $this->default_type);
                        }else{
                            $rrr['pay_channel'] = 2;
                            $opera = $this->comminssionPay($opera,$tokeninfo,$selectAmount * 100,$order_no);
                            if(\Tools::checkArrayResult($opera)){
                                 $this->orderModel->commit();
                                return \Tools::returnMsg(true, $rrr, $this->default_type);
                            }else{
                                 $this->orderModel->rollBack();
                                return \Tools::returnMsg(false, array(
                                    'code' => '10041',
                                    'message' => '订单生成失败'
                                ));
                            }
                        }
                    }else{
                         $this->orderModel->rollback();
                        return \Tools::returnMsg(false, array(
                            'code' => '10041',
                            'message' => '订单生成失败'
                        ));
                    }
                }

        }else{
            $res =
                 array(
                     'goods_list'           => array(
                         array(
                             'goods_spec'   => '15英寸 白色',
                             'name' =>'测试商量',
                             'cover'=> '/static/img/goods/p1.jpg',
                             'price_selling'=> '1500',
                             'stock_total'=>500,
                             'goods_sku'=>'asdfsadf24352',
                             'goods_code'=>'adf45454',
                             'select_num'=> '2'
                         ),
                         array(
                             'goods_spec'   => '15英寸 白色',
                             'name' =>'测试商量',
                             'cover'=> '/static/img/goods/p2.jpg',
                             'price_selling'=> '1500',
                             'stock_total'=>500,
                             'goods_sku'=>'asdfsadf24352',
                             'goods_code'=>'adf45454',
                             'select_num'=> '2'
                         )
                     ),
                     'goods_num'            => 4,
                     'is_show_coupon'       => 0,//是否显示优惠券入口  TODO 优惠券功能
                     'is_show_commission'   => 1,//是否显示佣金抵扣入口
                     'is_show_bill'         => 1,//是否显示发票开具入口
                     'postage_amount'       => 12,
                     'avail_amount'        => 50,//可用佣金
                     'total_amount'         => 3000,
                     'finial_amount'        => 2962,
                     'address'              => array(
                         'address'              => '',
                         'id'                   =>'',
                         'username'             =>'',
                         'phone'                =>''
                     )
                 );
            return \Tools::returnMsg(true, $res, $this->default_type);
        }
    }

    /**
     * 佣金支付订单
     * @param $opera
     * @param $tokeninfo
     * @param $selectAmount
     * @param $order_no
     * @return void
     */
    private function comminssionPay($opera,$tokeninfo,$selectAmount,$order_no){
        $userAccountModel = new \app\api\model\DataUserAccount();
        //扣减佣金
        $opera[] = $userAccountModel->decNum(array(
            'uuid'  => $tokeninfo['id']
        ),'freeze_amount',$selectAmount);
        $opera[] = $userAccountModel->decNum(array(
            'uuid'  => $tokeninfo['id']
        ),'avail_amount',$selectAmount);
        $opera[] = $userAccountModel->incNum(array(
            'uuid'  => $tokeninfo['id']
        ),'used_amount',$selectAmount);
        //修改订单状态
        $opera[] = $this->orderModel->saveData(array(
            'order_no'  => $order_no
        ),array(
            'pay_channel'  => 2,
            'status'       => 4,
            'update_at'     => \Tools::getDateTimeByTime(),
            'payment_datetime'     => \Tools::getDateTimeByTime(),
            'payment_remark'     => '佣金抵扣成功',
        ));
        return $opera;
    }
    /**
     * PUT
     * 重新支付
     * @return array|string
     */
    public function replaceorder(){
        if($this->request->debug != 1){
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo)){
                return \Tools::returnMsg(false,array(
                    'code'  => '100001',
                    'message'=>'未登录  请先登录'
                ),$this->default_type);
            }
            //从订单列表中发起支付
            //判断订单是否改价
            $order_no = input('order_no','','trim');//订单号
            if(empty($order_no)){
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            $orderInfo = $this->orderModel->getOne(array(
                'order_no'  => $order_no,
                'uuid'      => $tokeninfo['id']
            ),'payment_amount,id,payment_balance');
            if(empty($orderInfo)){
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            //校验佣金是否足够
            $commissModel = new \app\api\model\DataUserAccount();
            $commissionInfo = $commissModel->getOne(array(
                'uuid' => $tokeninfo['id']
            ), 'id,avail_amount,avail_credit,freeze_amount');
            $availAmount = 0;
            if (empty($commissionInfo) === FALSE) {
                $availAmount = $commissionInfo['avail_amount']-$commissionInfo['freeze_amount'];
            }
            if($orderInfo['payment_balance'] > $availAmount){
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'数据有误，请联系商家'
                ),$this->default_type);
            }
            //TODO 校验积分是否够
            //TODO 校验优惠券是否试用

            $body = sysconf('app_name') . '订单';
            $notify_url = $this->request->domain() . '/index/Order/mallnotify';      // 微信服务器异步通知
            $total_fee = $orderInfo['payment_amount'];                // 支付金额, 单位：分
            $time_start = \Tools::getDateTimeByTime();
            $time_expire = \Tools::getDateTimeByTime(time() + 7200);
            $trade_type = 'JSAPI';
            $mech_id = sysconf('merchant_no');
            $appid = sysconf('wx_appid');
            $key = sysconf('token');
            $spbill_create_ip = \Tools::getRemoteAddr();    // 客户端ip
            // 实例微信支付基类
            $weixinPay = new \Wxinpay($trade_type, $tokeninfo['openid'], $order_no, $body, $total_fee, $notify_url, $spbill_create_ip, 0, $appid, $mech_id, $key);

            // 发起微信支付
            $result = $weixinPay->pay();
            if ($result['code'] == 0) {      // 统一下单出错
                $this->orderModel->saveData(array(
                    'order_no' => $order_no
                ), array(
                    'status' => 0,
                    'excerpt' => $result['msg'],
                    'update_at' => \Tools::getDateTimeByTime()
                ));
                return \Tools::returnMsg(false, array(
                    'code' => '10041',
                    'message' => '订单付款失败'
                ));
            }
            // 获取预支付返回参成功
            $prepay_id = $result['msg']['prepay_id'];
            $res = $this->orderModel->saveData(array(
                'order_no' => $order_no
            ), array(
                'payment_trade' => $prepay_id,
                'payment_remark' => json_encode($result['msg']),
                'spbill_create_ip' => $spbill_create_ip,
                'update_at' => \Tools::getDateTimeByTime()
            ));
            if ($res === false) {
                return \Tools::returnMsg(false, array(
                    'code' => '10041',
                    'message' => '订单付款失败'
                ));
            }
            $result['msg']['time_expire'] = $time_expire;
            unset($result['msg']['appId']);
            $rrr = $result['msg'];
            $rrr['total_fee'] = sprintf("%.2f", $total_fee / 100);
            $rrr['body'] = $body;
            $rrr['merchant'] = sysconf('app_name') . '平台';
            $rrr['order_no'] = $order_no;

            return \Tools::returnMsg(true, $rrr, $this->default_type);
        }
        return \Tools::returnMsg(true,array(),$this->default_type);
    }

    /**
     * 再来一单
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function payagain(){
        if($this->request->debug != 1){
            $order_no = input('order_no','','trim');//订单编号
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo)){
                return \Tools::returnMsg(false,array(
                    'code'  => '100001',
                    'message'=>'未登录  请先登录'
                ),$this->default_type);
            }
            if(empty($order_no)){
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            //查一下订单商品
            $orderDetailModel = new \app\api\model\ShopOrderDetail();
            $lists = $orderDetailModel->getLists(array(
                'order_no'  => $order_no,
                'uuid'      => $tokeninfo['id']
            ));
            if(empty($lists)){
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'订单参数有误'
                ),$this->default_type);
            }
            $goodsModel = new \app\api\model\ShopGoodsItem();
            foreach($lists as &$lv){
                //查询商品状态 以及现在情况
                $goodsInfo = $goodsModel->getOne(array(
                    'id'    => $lv['product_id'],
                    'status'=>1
                ),'goods_sku,goods_code,goods_spec,price_selling,price_market,number_virtual,cover,name,stock_total');
                $res = 0;
                if(empty($goodsInfo) === FALSE){
                    $availStock = $goodsInfo['stock_total'] - $lv['stock_sales'];
                    if($availStock > 0) {
                        if($availStock >= $lv['stock_sales']){
                            $nowStock = $lv['stock_sales'];
                        }else{
                            $nowStock = $availStock;
                        }
                        $shopCartModel = new \app\api\model\ShopCart();
                        $cartData = array(
                            'goods_id'      => $lv['product_id'],
                            'goods_sku_id'  => $lv['goods_sku'],
                            'goods_num'     => $nowStock,
                            'user_id'       => $tokeninfo['id'],
                            'create_at'     => \Tools::getDateTimeByTime(),
                            'update_at'     => \Tools::getDateTimeByTime(),
                            'select'        => 1
                        );
                        $cartinfo = $shopCartModel->getOne(array(
                            'user_id'       => $tokeninfo['id'],
                            'goods_id'      => $lv['product_id'],
                            'goods_sku_id'  => $lv['goods_sku']
                        ));
                        if(empty($cartinfo)){
                            $res = $shopCartModel->addData($cartData);
                        }else{
                            //更新
                            $res = $shopCartModel->incNum(array(
                                'user_id'       => $tokeninfo['id'],
                                'goods_id'      => $lv['product_id'],
                                'goods_sku_id'  => $lv['goods_sku']
                            ),'goods_num',$nowStock);
                        }
                    }
                }
            }
            if($res){
                 return \Tools::returnMsg(true,$res,$this->default_type);
            }else{
                 return \Tools::returnMsg(false,array(
                    'code'  => '10006',
                    'message'=>'添加失败'
                ),$this->default_type);
            }
        }else{
            return \Tools::returnMsg(true,array(),$this->default_type);
        }
    }
    /**
     * GET
     * 订单列表
     * @return array|string
     */
    public function lists(){
        if($this->request->debug != 1){
            $page = input('page',1,'trim,intval');      //当前页码
            $size = input('size',10,'trim,intval');     //每页展示数量
            $status = input('status',0,'trim,intval');  //订单状态  0  全部   1  待付款  2  待发货  3  已发货
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo)){
                return \Tools::returnMsg(false,array(
                    'code'  => '100001',
                    'message'=>'未登录  请先登录'
                ),$this->default_type);
            }
            $where = [
                'payment_type'  => '0,1'
            ];
            if($status == 1){
                $where['status'] = '2,3';
            }elseif ($status == 2){
                $where['status'] = '4';
            }elseif($status == 3){
                $where['status'] = '5,6';
            }else{
                $where['status'] = '2,3,4,5,6';
            }
            $searchWhere = array(
                'uuid'  => $tokeninfo['id'],
            );
            $total = $this->orderModel->getNumBystatus($searchWhere,$where);
            $lists = $this->orderModel->getInLists($searchWhere,$where,
                'payment_amount,amount_express,order_no,create_at,status,amount_total,payment_type,payment_datetime,payment_status,payment_balance,number_goods,payment_credit,payment_coupon',
                '',array(
                'create_at'     => 'desc'
            ),[($page-1)*$size,$size]);
            $GoodsModel = new \app\api\model\ShopGoods();
            if(empty($lists) === FALSE){
                foreach($lists as &$lv){
                    $lv['payment_amount'] = sprintf("%.2f",$lv['payment_amount']/100);
                    $lv['status_name'] = $this->orderStatus[$lv['status']];
                    $lv['is_show_cancle'] = 0;//是否显示取消订单按钮  默认不显示
                    $lv['is_show_confirm'] = 0;//是否显示确认收货按钮  默认不显示
                    $lv['is_show_repay'] = 0;//是否显示重新支付按钮  默认不显示
                    $lv['is_show_again'] = 0;//是否显示再来一单按钮  默认不显示
                    $lv['is_show_reback'] = 0;//是否显示退货入口  默认不显示
                    $can_rebacktime = sysconf('can_rebacktime');
                    if(!isset($can_rebacktime)) $can_rebacktime = 7;
                    if($lv['status'] == 2){//待支付
                        $lv['is_show_repay'] = 1;
                        $orderTime = $lv['create_at'];
                        if(strtotime($orderTime) > time()-7200){
                            $lv['is_show_cancle'] = 1;//二小时内订单可以取消
                        }
                    }elseif($lv['status'] == 4){//已支付待发货
                        $lv['is_show_again'] = 1;
//                        if($lv['payment_datetime'] >= \Tools::getDateTimeByTime(strtotime("-".$can_rebacktime." days"))){
//                            $lv['is_show_reback'] = 1;
//                        }
                    }elseif($lv['status'] == 5){//已发货 待确认
                        $lv['is_show_again'] = 1;
                        $lv['is_show_confirm'] = 1;
//                        if($lv['payment_datetime'] >= \Tools::getDateTimeByTime(strtotime("-".$can_rebacktime." days"))){
//                            $lv['is_show_reback'] = 1;
//                        }
                    }elseif($lv['status'] == 6){//已完成
                        $lv['is_show_again'] = 1;
                        if($lv['payment_datetime'] >= \Tools::getDateTimeByTime(strtotime("-".$can_rebacktime." days"))){
                            $lv['is_show_reback'] = 1;
                        }
                        //判断是否申请过
                        $rebackModel = new \app\api\model\ShopOrderBack();
                         $has_reback = $rebackModel->where(array(
                             'order_no'  => $lv['order_no'],
                             'uuid'      =>$tokeninfo['id']
                         ))->findOrEmpty();
                         if(!$has_reback->isEmpty())$lv['is_show_reback'] = 0;
                    }
                    $lv['is_show_express'] = 0;//显示运费
                    $lv['is_show_balance'] = 0;//显示佣金抵扣
                    $lv['is_show_credit'] = 0;//显示积分抵扣
                    $lv['is_show_coupon'] = 0;//显示优惠券抵扣
                    if($lv['amount_express'] > 0){
                        $lv['amount_express'] = sprintf("%.2f",$lv['amount_express']/100);
                        $lv['is_show_express'] = 1;
                    }
                    if($lv['payment_balance'] > 0){
                        $lv['payment_balance'] = sprintf("%.2f",$lv['payment_balance']/100);
                        $lv['is_show_balance'] = 1;
                    }
                    if($lv['payment_credit'] > 0){
                        $lv['payment_credit'] = sprintf("%.2f",$lv['payment_credit']/100);
                        $lv['is_show_credit'] = 1;
                    }
                    if($lv['payment_coupon'] > 0){
                        $lv['payment_coupon'] = sprintf("%.2f",$lv['payment_coupon']/100);
                        $lv['is_show_coupon'] = 1;
                    }
                    //获取订单商品
                    $orderDetailModel = new \app\api\model\ShopOrderDetail();
                    $orderDetail = $orderDetailModel->getLists(array(
                        'uuid'  => $tokeninfo['id'],
                        'order_no'=>$lv['order_no']
                    ),'goods_code,goods_sku,goods_cover,goods_name,stock_sales,price_selling,goods_spec,product_id,goods_abridgeimg');
                    if(empty($orderDetail) === FALSE){
                        foreach($orderDetail as &$odv){
                            //根据规格id  获取商品id  用于订单页面进商品详情使用
                            $parentGoods = $GoodsModel->getOne(array(
                                'code'  => $odv['goods_code']
                            ),'id');
                            $odv['goods_id'] = empty($parentGoods) ? '0' : $parentGoods['id'];
                            $odv['price_selling'] = sprintf("%.2f",$odv['price_selling']/100);
                        }
                    }
                    $lv['orderDetail'] = $orderDetail;
                }
                return  \Tools::returnMsg(true,array(
                    'total' => $total,
                    'lists' => $lists
                ),$this->default_type);
            }else{
                return \Tools::returnMsg(true,array(
                    'total'     => 0,
                    'lists'     => []
                ),$this->default_type);
            }
        }else{
            return \Tools::returnMsg(true,array(
                'total' => 1,
                'lists' => array(
                    'status_name'   => '待付款',
                    'create_at'    => '2022-09-06 12:12:10',
                    'is_show_cancle'=> 1,
                    'is_show_confirm'=> 0,
                    'is_show_repay'=> 1,
                    'is_show_again'=> 0,
                    'is_show_express'=> 1,
                    'is_show_balance'=> 1,
                    'is_show_credit'=> 0,
                    'is_show_coupon'=> 0,
                    'payment_amount'=> '1200.00',
                    'amount_express'=> '12.00',
                    'payment_balance'=> '200.00',
                    'payment_credit'=> '0',
                    'payment_coupon'=> '0',
                    'number_goods'  =>3,
                    'order_no'  => '12121212',
                    'status'    => 2,
                    'payment_type'=> 0,
                    'orderDetail'=> array(
                        array(
                            'goods_abridgeimg'  => '/static/img/goods/p1.jpg',
                            'goods_name'        => '商品商品商品商品商品商品商品商品',
                            'goods_spec'        => '白色 15英寸',
                            'price_selling'     => '130.00',
                            'stock_sales'     => 2,
                        ),
                        array(
                            'goods_abridgeimg'  => '/static/img/goods/p2.jpg',
                            'goods_name'        => '商品商品商品商品商品商品商品商品',
                            'goods_spec'        => '黑色 15英寸',
                            'price_selling'     => '130.00',
                            'stock_sales'     => 1,
                        )
                    )
                )
            ),$this->default_type);
        }
    }

    /**
     * GET
     * 订单详情
     * @return void
     */
    public function info(){
        if($this->request->debug != 1){
            $order_no = input('order_no','','trim');//订单号
            if(empty($order_no)){
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo)){
                return \Tools::returnMsg(false,array(
                    'code'  => '100001',
                    'message'=>'未登录  请先登录'
                ),$this->default_type);
            }
            $orderInfo = $this->orderModel->getOne(array(
                'uuid'  => $tokeninfo['id'],
                'order_no'  => $order_no
            ),'address,phone,username,payment_datetime,trade_no,order_remark,amount_total,payment_amount,amount_express,order_no,create_at,status,amount_total,payment_type,payment_status,payment_amount,payment_balance,number_goods,payment_credit,payment_coupon');
            if(empty($orderInfo) === FALSE){
                $orderInfo['status_name'] = $this->orderStatus[$orderInfo['status']];
                    $orderInfo['is_show_cancle'] = 0;//是否显示取消订单按钮  默认不显示
                    $orderInfo['is_show_confirm'] = 0;//是否显示确认收货按钮  默认不显示
                    $orderInfo['is_show_repay'] = 0;//是否显示重新支付按钮  默认不显示
                    $orderInfo['is_show_again'] = 0;//是否显示再来一单按钮  默认不显示
                    $orderInfo['is_show_paytime'] = 0;//显示支付时间
                    if($orderInfo['status'] == 2){//待支付
                        $orderInfo['is_show_repay'] = 1;
                        $orderTime = $orderInfo['create_at'];
                        if(strtotime($orderTime) > time()-3600){
                            $orderInfo['is_show_cancle'] = 1;//一小时内订单可以取消
                        }
                    }elseif($orderInfo['status'] == 4){//已支付待发货
                        $orderInfo['is_show_again'] = 1;
                        $orderInfo['is_show_paytime'] = 1;
                    }elseif($orderInfo['status'] == 5){//已发货 待确认
                        $orderInfo['is_show_again'] = 1;
                        $orderInfo['is_show_paytime'] = 1;
                        $orderInfo['is_show_confirm'] = 1;
                    }elseif($orderInfo['status'] == 6){//已完成
                        $orderInfo['is_show_again'] = 1;
                        $orderInfo['is_show_paytime'] = 1;
                    }
                    $orderInfo['payment_amount'] = sprintf("%.2f",$orderInfo['payment_amount']/100);
                    $orderInfo['is_show_express'] = 0;//显示运费
                    $orderInfo['is_show_balance'] = 0;//显示佣金抵扣
                    $orderInfo['is_show_credit'] = 0;//显示积分抵扣
                    $orderInfo['is_show_coupon'] = 0;//显示优惠券抵扣
                    if($orderInfo['amount_express'] > 0){
                        $orderInfo['amount_express'] = sprintf("%.2f",$orderInfo['amount_express']/100);
                        $orderInfo['is_show_express'] = 1;
                    }
                    if($orderInfo['payment_balance'] > 0){
                        $orderInfo['payment_balance'] = sprintf("%.2f",$orderInfo['payment_balance']/100);
                        $orderInfo['is_show_balance'] = 1;
                    }
                    if($orderInfo['payment_credit'] > 0){
                        $orderInfo['payment_credit'] = sprintf("%.2f",$orderInfo['payment_credit']/100);
                        $orderInfo['is_show_credit'] = 1;
                    }
                    if($orderInfo['payment_coupon'] > 0){
                        $orderInfo['payment_coupon'] = sprintf("%.2f",$orderInfo['payment_coupon']/100);
                        $orderInfo['is_show_coupon'] = 1;
                    }
                    //获取订单商品
                    $orderDetailModel = new \app\api\model\ShopOrderDetail();
                    $orderDetail = $orderDetailModel->getLists(array(
                        'uuid'  => $tokeninfo['id'],
                        'order_no'=>$orderInfo['order_no']
                    ),'goods_sku,goods_cover,goods_name,stock_sales,price_selling,goods_spec,product_id,goods_abridgeimg');
                    $orderInfo['orderDetail'] = $orderDetail;
                    return \Tools::returnMsg(true,$orderInfo,$this->default_type);
            }else{
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
        }else{
            return \Tools::returnMsg(true,array(
                    'status_name'   => '待付款',
                    'create_at'    => '2022-09-06 12:12:10',
                    'payment_datetime'    => '2022-09-06 12:12:10',
                    'is_show_paytime'=> 1,
                    'is_show_cancle'=> 1,
                    'is_show_confirm'=> 0,
                    'is_show_repay'=> 1,
                    'is_show_again'=> 0,
                    'is_show_express'=> 1,
                    'is_show_balance'=> 1,
                    'is_show_credit'=> 0,
                    'is_show_coupon'=> 0,
                    'payment_amount'=> '1200.00',
                    'amount_total'=> '1400.00',
                    'amount_express'=> '12.00',
                    'payment_balance'=> '200.00',
                    'payment_credit'=> '0',
                    'payment_coupon'=> '0',
                    'number_goods'  =>3,
                    'order_no'  => '12121212',
                    'status'    => 2,
                    'payment_type'=> 0,
                    'order_remark'=> '尽快发货哦',
                    'address'=> '北京昌平',
                    'phone'=> '13555555555',
                    'username'=> '李思',
                    'orderDetail'=> array(
                        array(
                            'goods_abridgeimg'  => '/static/img/goods/p1.jpg',
                            'goods_name'        => '商品商品商品商品商品商品商品商品',
                            'goods_spec'        => '白色 15英寸',
                            'price_selling'     => '130.00',
                            'stock_sales'     => 2,
                        ),
                        array(
                            'goods_abridgeimg'  => '/static/img/goods/p2.jpg',
                            'goods_name'        => '商品商品商品商品商品商品商品商品',
                            'goods_spec'        => '黑色 15英寸',
                            'price_selling'     => '130.00',
                            'stock_sales'     => 1,
                        )
                    )
            ),$this->default_type);
        }
    }

    /**
     * PUT
     * 确认收货
     * @return void
     */
    public function confirm(){
        if($this->request->debug != 1){
            $order_no = input('order_no','','trim');//订单号
            if(empty($order_no)){
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo)){
                return \Tools::returnMsg(false,array(
                    'code'  => '100001',
                    'message'=>'未登录  请先登录'
                ),$this->default_type);
            }
            $orderInfo = $this->orderModel->getOne(array(
                'uuid'  => $tokeninfo['id'],
                'order_no'  => $order_no
            ),'id,order_no');
            if(empty($orderInfo)){
                 return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            $orderDetail = \app\api\model\ShopOrderDetail::where(array(
                'uuid'  => $tokeninfo['id'],
                'order_no'  => $order_no
            ))->findOrEmpty();
            if($orderDetail->isEmpty()){
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            $res = $this->orderModel->saveData(array(
                'id'    => $orderInfo['id']
            ),array(
                'status'    =>6,
                'finish_datetime' => \Tools::getDateTimeByTime(),
                'update_at'=>\Tools::getDateTimeByTime()
            ));

            if($res){
                return \Tools::returnMsg(true,$res,$this->default_type);
            }else{
                return \Tools::returnMsg(false,array(
                    'code'  => '10008',
                    'message'=>'确认失败，请重试'
                ),$this->default_type);
            }
        }else{
            return \Tools::returnMsg(true,[],$this->default_type);
        }
    }
    /**
     * DELETE
     * 取消订单
     * @return void
     */
    public function cancle(){
        if($this->request->debug != 1){
            $order_no = input('order_no','','trim');//订单号
            if(empty($order_no)){
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo)){
                return \Tools::returnMsg(false,array(
                    'code'  => '100001',
                    'message'=>'未登录  请先登录'
                ),$this->default_type);
            }
            $orderInfo = $this->orderModel->getOne(array(
                'uuid'  => $tokeninfo['id'],
                'order_no'  => $order_no
            ),'id,uuid,order_no,payment_balance');
            if(empty($orderInfo)){
                 return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
            $opera = [];
            $this->orderModel->startTrans();
            $opera[] = $this->orderModel->saveData(array(
                'id'    => $orderInfo['id']
            ),array(
                'status'    =>0,
                'cancel_remark'   => '用户自行取消未支付的订单',
                'cancel_datetime' => date('Y-m-d H:i:s'),
                'update_at'=>\Tools::getDateTimeByTime()
            ));
            //若有佣金  返回
            //若有优惠券  返回
            //若有积分  返回
            //归还库存
            $opera = OrderService::stock($orderInfo['order_no'],$opera,1);

            //如果订单有佣金抵扣  归还佣金
            if ($orderInfo['payment_balance'] > 0){
                $DatauserAccountModel = new \app\api\model\DataUserAccount();
                $opera[] = $DatauserAccountModel->incNum(['uuid'=>$orderInfo['uuid']],'avail_amount',$orderInfo['payment_balance']);
                $opera[] = $DatauserAccountModel->decNum(['uuid'=>$orderInfo['uuid']],'freeze_amount',$orderInfo['payment_balance']);
            }
            //TODO 归还优惠券
            //TODO 归还积分
            sysoplog('取消订单','用户：自行取消订单：'.$orderInfo['order_no']);
            if(\Tools::checkArrayResult($opera)){
                $this->orderModel->commit();
                return \Tools::returnMsg(true,$opera,$this->default_type);
            }else{
                $this->orderModel->rollBack();
                return \Tools::returnMsg(false,array(
                    'code'  => '10008',
                    'message'=>'取消失败，请重试'
                ),$this->default_type);
            }
        }else{
            return \Tools::returnMsg(true,1,$this->default_type);
        }
    }

    /**
     * 获取退换货规则
     * @return array|string
     */
    public function getbackrule(){
        $detail = sysconf('order_backrule');
        if(empty($detail)) $detail = '';
        return \Tools::returnMsg(true,array(
            'content'   => $detail
        ),$this->default_type);
    }

    /**
     * 申请退货
     * @return array|string|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function uprebackapply(){
        $order_no = input('order_no','','trim');//需退货的订单号
        $remark    = input('remark','','trim');//退换货原因
        if(empty($order_no)){
            return \Tools::returnMsg(false,array(
                'code'  => '10004',
                'message'=>'参数有误'
            ),$this->default_type);
        }
        $tokeninfo = $this->request->tokeninfo;
        if(empty($tokeninfo)){
            return \Tools::returnMsg(false,array(
                'code'  => '100001',
                'message'=>'未登录  请先登录'
            ),$this->default_type);
        }

        $detailModel = new \app\api\model\ShopOrderDetail();
        $detail = $detailModel->getLists(array(
            'order_no'  => $order_no,
            'uuid'      =>$tokeninfo['id']
        ));
        if(empty($detail)){
            return \Tools::returnMsg(false,array(
                'code'  => '10004',
                'message'=>'参数有误'
            ),$this->default_type);
        }
        $backdetail = [];
        foreach ($detail as &$dv){
            $backdetail[] = array(
                'order_no' => $order_no,
                'goods_sku' => $dv['goods_sku'],
                'goods_code' => $dv['goods_code'],
                'goods_spec' => $dv['goods_spec'],
                'goods_name' => $dv['goods_name'],
                'goods_cover' => $dv['goods_cover'],
                'goods_abridgeimg' => $dv['goods_cover'],
                'price_market' => $dv['price_market'],
                'price_selling' => $dv['price_selling'],
                'product_id' => $dv['product_id'],
                'num' => $dv['stock_sales'],
                'uuid' => $tokeninfo['id'],
                'apply_no' => \Common::uniqidDate('16','B'),
                'create_at' => \Tools::getDateTimeByTime()
            );
        }
         //判断订单是否申请过退货
         $rebackModel = new \app\api\model\ShopOrderBack();
         $has_reback = $rebackModel->where(array(
             'order_no'  => $order_no,
             'uuid'      =>$tokeninfo['id']
         ))->select()->toArray();
         if(empty($has_reback) === FALSE){
             return \Tools::returnMsg(false,array(
                'code'  => 100012,
                'message'   => '每笔订单只能申请一次退货，您已经申请过。请确认或者联系客服'
            ),$this->default_type);
         }
        //更改订单状态 为退货
        //添加退货记录
        $opera = [];
        $this->orderModel->startTrans();
         sysoplog('提交退货',"订单：".$order_no."，提交退货申请");
        $opera[] = $this->orderModel->saveData(array(
            'uuid'      => $tokeninfo['id'],
            'order_no'  => $order_no
        ),array(
            'status'    => 7,
            'reback_remark'=>$remark,
            'update_at'   => \Tools::getDateTimeByTime(),
            'reback_date'   => \Tools::getDateTimeByTime()
        ));

        if(count($backdetail) > 1){
            $opera[] = $rebackModel->addInfo($backdetail);
        }else {
            $opera[] = $rebackModel->addData($backdetail[0]);
        }
        if(\Tools::checkArrayResult($opera)){
            $this->orderModel->commit();
            return \Tools::returnMsg(true,$opera,$this->default_type);
        }else{
            $this->orderModel->rollback();
            return \Tools::returnMsg(false,array(
                'code'  => 100012,
                'message'   => '提交失败，请重试'
            ),$this->default_type);
        }
    }

    /**
     * 退货记录
     * @return array|string
     */
    public function rebacklist(){
        $page = input('page',1,'trim,intval');
        $size = input('size',10,'trim,intval');

        $tokeninfo = $this->request->tokeninfo;
        if(empty($tokeninfo)){
            return \Tools::returnMsg(false,array(
                'code'  => '100001',
                'message'=>'未登录  请先登录'
            ),$this->default_type);
        }
        $total = $this->orderModel->checkNum(array(
            'uuid'  => $tokeninfo['id'],
            'payment_type'=>0,
            'status'=> 7
        ));
        $orderList = [];
        if($total > 0) {
            $orderList = $this->orderModel->getAllData(array(
                'uuid' => $tokeninfo['id'],
                'payment_type'=>0,
                'status' => 7
            ), 'order_no,reback_date', '', array(
                'reback_date' => 'desc'
            ), array(($page - 1) * $size, $size));
            if(empty($orderList) === FALSE){
                foreach($orderList  as &$lv){
                    $goodsList = [];
                    $backGoodsModel = new \app\api\model\ShopOrderBack();
                    $goodsList = $backGoodsModel->whereInInfo(array(
                        'order_no'  => $lv['order_no'],
                        'uuid'      =>$tokeninfo['id']
                    ),'status','0,1','goods_name,goods_spec,goods_cover,goods_abridgeimg as img,status,num,price_selling as price');
                    $goodsnum = 0;
                    $statusname = '';
                    $status = 0;
                    if(empty($goodsList) === FALSE){
                        foreach($goodsList as &$gv){
                            if($gv['status'] == 0){
                                $statusname = '审核中';
                            }elseif ($gv['status'] == 1){
                                $statusname = '已审核';
                            }elseif ($gv['status'] == 2){
                                $statusname = '已驳回';
                            }
                            $goodsnum += $gv['num'];
                            $status = $gv['status'];
                        }
                    }
                    $lv['status_name'] = $statusname;
                    $lv['status'] = $status;
                    $lv['goods_num'] = $goodsnum;
                    $lv['goodsList'] = $goodsList;
                }
            }
        }
        return \Tools::returnMsg(true,array(
            'total'     =>$total,
            'lists'     =>$orderList
        ),$this->default_type);
    }
    /**
     * 推销退货申请
     * @return array|string
     */
    public function canclereback(){
        $order_no = input('order_no','','trim');//订单号
        $tokeninfo = $this->request->tokeninfo;
        if(empty($tokeninfo)){
            return \Tools::returnMsg(false,array(
                'code'  => '100001',
                'message'=>'未登录  请先登录'
            ),$this->default_type);
        }
        $info = $this->orderModel->getOne(array(
                'uuid' => $tokeninfo['id'],
                'payment_type'=>0,
                'status' => 7,
                'order_no'=>$order_no
        ));
        if(empty($info)){
            return \Tools::returnMsg(false,array(
                'code'  => '10004',
                'message'=>'参数有误'
            ),$this->default_type);
        }
        $opera  = [];
        $this->orderModel->startTrans();
         sysoplog('撤销退货',"订单：".$order_no."，取消退货申请");
        $opera[] = $this->orderModel->saveData(array(
                'uuid' => $tokeninfo['id'],
                'payment_type'=>0,
                'status' => 7,
                'order_no'=>$order_no
        ),array(
            'status'    => 6,
            'update_at' => \Tools::getDateTimeByTime()
        ));
        $backModel = new \app\api\model\ShopOrderBack();
        $opera[] = $backModel->saveData(array(
            'order_no'  => $order_no,
            'uuid'      => $tokeninfo['id']
        ),array(
            'status'    => 3
        ));
        if(\Tools::checkArrayResult($opera)) {
            $this->orderModel->commit();
            return \Tools::returnMsg(true, [], $this->default_type);
        }else{
            $this->orderModel->rollBack();
            return \Tools::returnMsg(false,array(
                'code'  => '100015',
                'message'=>'取消失败'
            ),$this->default_type);
        }
    }

        /**
     * 订单跟踪
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderTrace(){
        $order_no = input('order_no','','trim');//订单号
        if(empty($order_no)){
            return \Tools::returnMsg(false,array(
                'code'  => '10004',
                'message'=>'参数有误'
            ),$this->default_type);
        }
        $tokeninfo = $this->request->tokeninfo;
        if(empty($tokeninfo)){
            return \Tools::returnMsg(false,array(
                'code'  => '100001',
                'message'=>'未登录  请先登录'
            ),$this->default_type);
        }
         $order = $this->orderModel->getOne(array(
                'uuid' => $tokeninfo['id'],
                'order_no'=>$order_no
        ));
        if(empty($order)){
            return \Tools::returnMsg(false,array(
                'code'  => '10004',
                'message'=>'参数有误'
            ),$this->default_type);
        }
        $data = [];
        //初始化数据
        $order_tips = '已下单';
        $order_traces = [];
        $traces = [];//物流轨迹
        $shipment = [//发货
            'title' => '已发货',
            'tips' => '',
            'time' => '',
        ];
        $finish = [//交易完成
            'title' => '交易完成',
            'tips' => '',
            'time' => '',
        ];
        $data['trade_no'] = $order['trade_no'];
        $sendModel = new \app\api\model\ShopOrderSend();
        $orderSend = $sendModel::getDetail('*',array(
            'order_no'  => $order_no,
            'uuid'      =>$tokeninfo['id']
        ));
        if(empty($orderSend)){
            return \Tools::returnMsg(false,array(
                'code'  => '10004',
                'message'=>'参数有误'
            ),$this->default_type);
        }
        $addresser = DataAddresser::getDetail('*',['id'=>$orderSend['send_id']]);
        $send_address = '';
        if(empty($addresser) === FALSE){
            $province = DataCity::getProvince($addresser['province_id']);
            $city = DataCity::getCity($addresser['city_id']);
            $send_address .= $province;
            $send_address .= $city;
        }
        $data['mobile'] = $orderSend['address_phone'];
        $address = explode('市',$orderSend['address_content']);
        $data['to_address'] = $address[0].'市';
        $data['from_address'] = $send_address;
        $data['express_no'] = $orderSend['company_code'];
        $key = sysconf('kd100_appkey');// 客户授权key
        $kd100_customer = sysconf('kd100_customer');// 查询公司编号
        $expressage = (new Kd100($kd100_customer, $key));
        $expressage->logistics($data);
        $order_delivery = ShopOrderSend::getDetail('company_name',['order_no'=>$order['order_no']]);
        $traces = $expressage->logisticsFormat();

        $detailModel = new \app\api\model\ShopOrderDetail();
        $ordergoods = $detailModel->getOne(array(
            'order_no'  => $order['order_no'],
            'uuid'      =>$tokeninfo['id']
        ));
        $image = $ordergoods['goods_cover'];
        //获取不到物流轨迹时
        if ($traces == false) {
            $error = $expressage->getError();
            $error = json_decode($error,true);
            if($error['result'] == false){
                $traces[] = [$error['message']];
            }
        } else {
            foreach ($traces as &$item) {
                $item = array_values(array_unique($item));
            }
        }
        //待收货
            if ($order['status'] == 5) {
                $shipment['tips'] = '商品已出库';
                $shipment['time'] = $order['trade_send_time'];
            }
            //确认收货
            if ($order['status'] == 6) {
                $order_tips = '交易完成';
                $finish['tips'] = '订单交易完成';
                $finish['time'] = $order['update_at'];
            }
            //数据合并
            $order_traces = [
                'order' => [
                    'tips' => $order_tips,
                    'image'=>$image,
                    'count' => $order['number_goods'],
                    'invoice_no' => $order['trade_no'],
                    'shipping_name' => empty($order_delivery['company_name']) ? '-' : $order_delivery['company_name'],
                ],
                'take' => [
                    'contacts' => $order['username'],
                    'mobile' => $order['phone'],
                    'address' => $order['address'],
                ],
                'finish' => $finish,
                'delivery' => [
                    'title' => '运输中',
                    'traces' => $traces
                ],
                'shipment' => $shipment,
                'buy' => [
                    'title' => '已下单',
                    'tips' => '订单提交成功',
                    'time' => $order['payment_datetime']
                ],
            ];
            return \Tools::returnMsg(true,$order_traces,$this->default_type);
    }
}
